package com.kady.utils;

import com.kady.contant.ExceptionConstant;
import com.kady.contant.MessageConstant;
import com.kady.entity.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/26
 * \* Time: 16:15
 * \* 千峰JAVA2101班
 * \* Description: 上传工具类
 * \
 */
public class UploadUtil {
    public static Object uploadFile(HttpServletRequest req, String partName, String filePath) throws IOException, ServletException {
        Part part = req.getPart(partName);
//        part.getSubmittedFileName()
        String cd = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);

        //判断文件是否为空
        if(filename.isEmpty()){
            return new ResultVO(false, ExceptionConstant.NOT_FILE_UPLOAD);
        }
        //获取文件后缀名并创建新的文件名
        String suffixName = filename.substring(filename.lastIndexOf(MessageConstant.POINT));
        String newFileName = UUID.randomUUID().toString().replaceAll("-","").concat(suffixName);
        //获取文件上传的目标路径
        String uploadPath = req.getSession().getServletContext().getRealPath(filePath);

        File file = new File(uploadPath,newFileName);

        if(!file.getParentFile().exists()){
            file.getParentFile().mkdir();
        }

        part.write(uploadPath + newFileName);

        return filePath + newFileName;
    }
}
